// controllers/dishController.js
const pool = require('../config/db');
const { sendResponse } = require('../utils/response');

// 获取所有菜品
const getAllDishes = async (req, res) => {
  try {
    const [rows] = await pool.execute('SELECT * FROM dishes WHERE status = 1');
    sendResponse(res, 200, '获取菜品成功', rows);
  } catch (error) {
    sendResponse(res, 500, '获取菜品失败', error.message);
  }
};

// 获取单个菜品
const getDishById = async (req, res) => {
  const { id } = req.params;
  try {
    const [rows] = await pool.execute('SELECT * FROM dishes WHERE id = ? AND status = 1', [id]);
    if (rows.length === 0) {
      return sendResponse(res, 404, '菜品未找到');
    }
    sendResponse(res, 200, '获取菜品成功', rows[0]);
  } catch (error) {
    sendResponse(res, 500, '获取菜品失败', error.message);
  }
};

// 创建菜品（需要管理员权限）
const createDish = async (req, res) => {
  const { category_id, name, price, description, is_spicy, inventory } = req.body;
  // 获取上传的图片路径
  const image_url = req.file ? `/uploads/${req.file.filename}` : null;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    const [result] = await connection.execute(
      'INSERT INTO dishes (category_id, name, price, image_url, description, is_spicy, inventory) VALUES (?, ?, ?, ?, ?, ?, ?)',
      [category_id, name, price, image_url, description, is_spicy || 0, inventory || 999]
    );
    await connection.commit();
    sendResponse(res, 201, '创建菜品成功', { id: result.insertId });
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '创建菜品失败', error.message);
  } finally {
    connection.release();
  }
};

// 更新菜品（需要管理员权限）
const updateDish = async (req, res) => {
  const { id } = req.params;
  const { category_id, name, price, description, is_spicy, inventory } = req.body;
  // 获取上传的图片路径（如果有新图片上传）
  const image_url = req.file ? `/uploads/${req.file.filename}` : req.body.image_url;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    const [result] = await connection.execute(
      'UPDATE dishes SET category_id = ?, name = ?, price = ?, image_url = ?, description = ?, is_spicy = ?, inventory = ? WHERE id = ?',
      [category_id, name, price, image_url, description, is_spicy, inventory, id]
    );
    if (result.affectedRows === 0) {
      return sendResponse(res, 404, '菜品未找到');
    }
    await connection.commit();
    sendResponse(res, 200, '更新菜品成功');
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '更新菜品失败', error.message);
  } finally {
    connection.release();
  }
};

// 删除菜品（需要管理员权限，逻辑删除）
const deleteDish = async (req, res) => {
  const { id } = req.params;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    const [result] = await connection.execute('UPDATE dishes SET status = 0 WHERE id = ?', [id]);
    if (result.affectedRows === 0) {
      return sendResponse(res, 404, '菜品未找到');
    }
    await connection.commit();
    sendResponse(res, 200, '删除菜品成功');
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '删除菜品失败', error.message);
  } finally {
    connection.release();
  }
};

module.exports = {
  getAllDishes,
  getDishById,
  createDish,
  updateDish,
  deleteDish
};